class ReporterArticlesController < ApplicationController
  before_filter :authenticate
  layout "reporter"
    
  # GET /articles
  # GET /articles.xml
  def index
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @user = current_user
    @filter = params[:filter].nil? ? {} : params[:filter]
    @page = params[:page].nil? ? nil : params[:page]
    @articles = Article.reporter_articles_list(current_user, @filter).paginate :page=>params[:page], :order=>'created_at desc', :per_page => 5
    # @articles = Article.all.paginate :page=>(params[:page].to_i - 1), :order=>'created_at desc', :per_page => 3 if @articles.count == 0 && !params[:page].nil?
    @users = User.all
    
    # article status list
    @article_statuses = ArticleStatus.all
    
    #article channel list
    @channels = Channel.all
    

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @articles }
      format.js { render '_articles.js.erb' }
    end
  end
  
  # GET /articles/new
  # GET /articles/new.xml
  def new
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @article = Article.new
    @event = Event.find(params[:event_id]) if !params[:event_id].nil?
    @article_statuses = ArticleStatus.all.collect {|p| [ p.title, p.id ] }
    
    # event list
    @events = Event.all.collect {|p| [ p.title, p.id ] }
    # @events << ["none", ""]
    
    # channel list
    @channels = Channel.find(:all, :order => "title").collect {|p| [ p.title, p.id ] }
    
    # images
    @images = Image.all
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @article }
    end
  end
  
  # GET /articles/1
  # GET /articles/1.xml
  def show
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @user = current_user
    begin
      @article = Article.find(params[:id])
    rescue ActiveRecord::RecordNotFound      
      return nil
    end

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @article }
    end
  end

  # GET /articles/1/edit
  def edit
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @article = Article.find(params[:id])
    @event = @article.event if !@article.event.nil?
    @article_statuses = ArticleStatus.all.collect {|p| [ p.title, p.id ] }
    
    # images
    if !@event.nil?
      @images = @event.images
    else
      @images = Image.all
    end
    
    # channel list
    @channels = Channel.all.collect {|p| [ p.title, p.id ] }
    
    # event list
    @events = Event.all.collect {|p| [ p.title, p.id ] }
    
  end

  def save
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    # event list
    @events = Event.all.collect {|p| [ p.title, p.id ] }
    
    # channel list
    @channels = Channel.all.collect {|p| [ p.title, p.id ] }
    
    # images
    @images = Image.all
    
    if !params[:id].nil?
      # FIND EXIST ARTICLE
      @article = Article.find(params[:id])
      @user = current_user
      # test if status is APPROVING
      if !@article.reporter_edit?(@user)
        respond_to do |format|
          format.html {
            flash[:error] = "Article can't be edited because its status is: APPROVING."
            redirect_to({:controller => 'reporter_articles',
                                      :action => 'show', :id => @article.id})
                      }
          format.xml  { head :ok }
        end
      else
        # CHANGE STATUS
        @article.article_status = ArticleStatus.get('MODIFY')
        
        # save article history
        @article.save_history(current_user.username, request.remote_addr)
    
        respond_to do |format|
          if @article.update_attributes(params[:article])
            format.html { redirect_to({:controller => 'reporter_articles', :action => 'show', :id => @article.id}, :notice => 'Article was successfully updated.') }
            format.xml  { head :ok }
          else
            format.html { render :action => "edit" }
            format.xml  { render :xml => @article.errors, :status => :unprocessable_entity }
          end
        end
      end      
    else
    # CREATE NEW ARTICLE
      @article = Article.new(params[:article])
      
      # CHANGE STATUS
      @article.article_status = ArticleStatus.get('NEW')
      
      # Add current user
      @article.user = current_user
      
      respond_to do |format|
        if @article.save
          format.html { redirect_to({:controller => 'reporter_articles', :action => 'show', :id => @article.id}, :notice => 'Article was successfully updated.') }
          format.xml  { render :xml => @article, :status => :created, :location => @article }
        else
          format.html { render :action => "new" }
          format.xml  { render :xml => @article.errors, :status => :unprocessable_entity }
        end
      end
    end
  end
  

  def destroy
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))    
    
    @user = current_user
    @article = Article.find(params[:id])
    
    if !@article.reporter_edit?  (@user)      
        respond_to do |format|
          format.html {
            flash[:error] = "Article can't be deleted because its status is: APPROVING."
            redirect_to({:controller => 'reporter_articles'})
          }
          format.xml  { head :ok }
          format.js { render :text => 'error' }
        end
        return nil
    else
      # destroy article
      @article.destroy
    end
    

    # @page = params[:page].nil? ? 1 : params[:page]
    
    # return nil
  
    #@articles = Article.all.paginate :page=>params[:page], :order=>'created_at desc', :per_page => 3
    
    respond_to do |format|
        format.html { redirect_to({:controller => 'reporter_articles'}, :notice => "Article was successfully deleted.") }
        format.xml  { head :ok }
        format.js { render 'destroy.js.erb' }
    end
  end
  
  def delete_selected
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @ids = params[:ids]
    @user = current_user
    
      @ids.each do |obj|
      @article = Article.find(obj[0])
        if !@article.reporter_edit?(@user)      
            respond_to do |format|
              format.html {
                flash[:error] = "Article can't be deleted because its status is: APPROVING."
                redirect_to({:controller => 'reporter_articles'})
              }
              format.xml  { head :ok }
              format.js { render :text => 'error' }
            end
            return nil
        else
          @article.destroy
        end
      end
    
    
    respond_to do |format|
        format.html { redirect_to({:controller => 'reporter_articles'}, :notice => "Articles was successfully deleted.") }
        format.xml  { head :ok }
        format.js { render 'destroy.js.erb' }
    end
  end
  
  def published
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @article = Article.find(params[:id])
    
    if @article.published
      @article.published = false
      @turn = "off"
      @do = "un"
      @title = "No"
    else
      @article.published = true
      @turn = "on"
      @do = ""
      @title = "Yes"
    end
    
    respond_to do |format|
      if @article.save
        format.html { redirect_to(articles_url, :notice => "Article was successfully #{@do}published.") }
        format.js { render 'published.js.erb' }
      else
        format.html { redirect_to(articles_url, :notice => "Article didn\'t been #{@do}published.") }
        format.js { render 'published_err.js.erb' }
      end
    end
      
  end
  
  def approving
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('REPORTER'))
    
    @article = Article.find(params[:id])
    @article.article_status = ArticleStatus.get('APPROVING')
    
    # add approval history
    @approval = @article.article_approvals.create(:status => @article.article_status.title, :user_id => current_user.id)
    
    respond_to do |format|
        if @article.update_attributes(params[:article])
          format.html { redirect_to({:controller => 'reporter_articles'}, :notice => "Article '#{@article.title}' was in approving list.") }
          format.xml  { head :ok }
        else
          format.html { redirect_to({:controller => 'reporter_articles'}, :notice => "Can't move article to approving list.") }
          format.xml  { render :xml => @article.errors, :status => :unprocessable_entity }
        end
    end
  end
  
  def insert_image_box
    @images = Event.find(params[:id]).images
    render :layout => false
  end

end
